<template>
	<div class="page-sensorsdata">
		<section>
			<div class="pageheader">
				<div class="pageheader-left">
					{{pageName}}
				</div>
				<div class="pageheader-right">
					<div class="btn">
						<i class="el-icon-document-add"></i>
						<span class='' @click="openSaveDialog">
							保存
						</span>
					</div>
				</div>
			</div>
		</section>
		<div class="sendorsdata-body">
			<router-view></router-view>
		</div>

		<!-- 新建组件，配置相关属性并添加到概览 -->
		<el-dialog :visible.sync="setupComponentVisible" width="650px" class="setup-component" :before-close='reset'>
			<div slot='title' class="setupComponentTitle">
				<div class="title-item" @click="setupForm.saveType = 'comment'">
					<span :class="{active: setupForm.saveType == 'comment'}">保存到概览</span>
				</div>
				<div class="title-item" @click="setupForm.saveType = 'bookmark'">
					<span :class="{active: setupForm.saveType == 'bookmark'}">保存到书签</span>
				</div>
			</div>
			<el-form v-show="setupForm.saveType == 'comment'" ref="setupForm" :model="setupForm" :rules="setupRules" label-width="120px"
				label-position='left'>
				<el-form-item label="选择页面" prop="pageId">
					<el-select v-model="setupForm.pageId" placeholder="请选择页面">
						<el-option v-for="dict in userPageOptions" :key="dict.id" :label="dict.overviewName"
							:value="dict.id"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="组件名称" prop="componentName">
					<el-input v-model="setupForm.componentName" placeholder="请输入组件名称" />
				</el-form-item>
				<template v-if="setupForm.analyticsType == 'event'">
					<el-form-item label="时间粒度" prop="dateUnit">
						<el-select v-model="setupForm.dateUnit" placeholder="请选择时间粒度">
							<el-option v-for="dict in dateUnitOptions" :key="dict.dictValue" :label="dict.dictLabel"
								:value="dict.dictValue"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="图表类型" prop="chartType" class="chartype">
						<div class="chart-type-item"
							:class="{active: index == activeChartTypeIndex, forbidden: item.chartName == '环图'}"
							v-for="(item, index) in chartTypeOptions" @click="chartTypeChangeFun(index, item)">
							<i :class="item.chartIcon"></i>
							<span>{{item.chartName}}</span>
							<div class="check-tag" v-if="index == activeChartTypeIndex">
								<i class="el-icon-check"></i>
							</div>
						</div>
					</el-form-item>
					<el-form-item label="显示项类型" v-show="currChartItemOptions.length != 0" prop="showItem">
						<el-checkbox-group v-model="setupForm.showItem">
							<el-checkbox v-for="dict in currChartItemOptions" :key="dict.dictValue"
								:label="dict.dictValue">
								{{dict.dictLabel}}
							</el-checkbox>
						</el-checkbox-group>
					</el-form-item>
				</template>
				<el-form-item label="显示窗口类型" class="window-type" prop="windowType">
					<div class="window-type-item"
						:class="{active: index == windowTypeIndex, forbidden: setupForm.chartType != 6 && item.dictValue =='small'}"
						v-for="(item, index) in windowTypeOptions" :key='item.dictValue'
						@click="windowTypeChangeFun(index, item)">
						<div class="window-type-back" :class="[`${item.dictValue}`]"></div>
						<div class="label">
							{{item.dictLabel}}
						</div>
						<div class="check-tag" v-if="index == windowTypeIndex">
							<i class="el-icon-check"></i>
						</div>
					</div>
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input v-model="setupForm.remark" placeholder="请输入备注" />
				</el-form-item>

			</el-form>
			<el-form v-show="setupForm.saveType == 'bookmark'" ref="bookmarkForm" :model="setupForm" :rules="setupRules" label-width="120px"
				label-position='left'>
				<el-form-item label="组件名称" prop="componentName">
					<el-input v-model="setupForm.componentName" placeholder="请输入组件名称" />
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input v-model="setupForm.remark" placeholder="请输入备注" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="launchSubmit">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>

	</div>
</template>

<script>
	import {
		getAllGroupAndOverview,
		listTeam,
		getTeam,
		delTeam,
		addTeam,
		updateTeam,
		exportTeam
	} from "@/api/overview/team";
	import {
		listType
	} from "@/api/overview/type";
	import {
		listPage,
		getPage,
		addPage
	} from "@/api/overview/page";
	import {
		listItems,
		getItems,
		delItems,
		addItems,
		updateItems,
		exportItems
	} from "@/api/overview/items";
  import {addMark, updateMark} from "@/api/overview/mark";
	export default {
		name: "sensorsdata",
		components: {},
		data() {
			return {
				windowTypeOptions: [],

				// 时间粒度字典
				dateUnitOptions: [],
				// 图表类型字典
				chartTypeOptions: [],
				// 显示项类型字典
				showItemOptions: [],
				userPageOptions: [],

				//添加到概览弹窗
				setupComponentTitle: '',
				setupComponentVisible: false,
				setupForm: {
					saveType: 'comment',
					pageId: null,
					componentName: null,
					analyticsType: null,
					remark: null,
					dateUnit: null,
					chartType: null,
					showItem: [],
					windowType: null,
					queryRule: null,
					sortNo: null,
					paramField1: null,
					paramField2: null,
				},

				activeChartTypeIndex: null,
				windowTypeIndex: null,

				setupRules: {
					pageId: [{
						required: true,
						message: '请输入选择概览页',
						trigger: 'blur'
					}, ],
					componentName: [{
						required: true,
						message: '请输入组件名',
						trigger: 'blur'
					}, ],
					dateUnit: [{
						required: true,
						message: '请选择事件粒度',
						trigger: 'blur'
					}, ],
					chartType: [{
						required: true,
						message: '请选择图表类型',
						trigger: 'blur'
					}, ],
					showItem: [{
						required: true,
						message: '请选择显示项类型',
						trigger: 'blur'
					}, ],
					windowType: [{
						required: true,
						message: '请选择窗口类型',
						trigger: 'blur'
					}, ],
				},
			}
		},
		computed: {
			currChartItemOptions() {
				let currChartItemOptions = []
				let checkedItem = []
				let currentChart = this.chartTypeOptions[this.activeChartTypeIndex] || {}
				let showItems = currentChart.valueItem
				if (showItems) {
					this.showItemOptions.forEach(opt => {
						if (showItems.indexOf(opt.dictValue) != -1) {
							currChartItemOptions.push(opt)
							checkedItem.push(opt.dictValue)
						}
					})
					this.setupForm.showItem = checkedItem
					return currChartItemOptions
				} else {
					return []
				}
			},

			pageName() {
				return this.$route.name
			}
		},
		watch: {
			"setupForm.pageId": {
				handler: function(newval, oldval) {
					console.log(newval, oldval)
					let pageId = newval
					getPage(pageId).then(({ data }) => {
						this.setupForm.sortNo = data.overviewItemList.length + 1
					})
				}
			}
		},
		mounted() {
			this.$EventBus.$on('commitComponentQueryJson', (requestJson) => {
				this.submitForm(requestJson)
			})
		},
		beforeDestroy() {
			this.$EventBus.$off('commitComponentQueryJson')
		},
		created() {
			this.getChartTypeData()
			this.getUserPageData()
			let analyticsType = this.$route.path.split('/').pop()
			// console.log(analyticsType.pop())
			this.setupForm.analyticsType = analyticsType
			this.getDicts("sys_window_type").then(response => {
				this.windowTypeOptions = response.data;
			});
			this.getDicts("sys_time_unit_type").then(response => {
				this.dateUnitOptions = response.data;
			});
			this.getDicts("sys_overview_item_type").then(response => {
				this.showItemOptions = response.data;
			});
		},

		methods: {

			//获取图表类型
			getChartTypeData() {
				let parmas = {};
				listType(parmas).then(response => {
					this.chartTypeOptions = response.rows;
					this.chartTypeChangeFun(0, this.chartTypeOptions[0])
				});
			},

			chartTypeChangeFun(index, item) {
				if (item.chartName == '环图') return
				this.setupForm.chartType = item.id
				this.activeChartTypeIndex = index
				this.setupForm.windowType = null
				this.windowTypeIndex = null
			},

			openSaveDialog() {
				this.setupComponentVisible = true
				this.setupComponentTitle = '添加到概览'
			},

			reset(done) {
				this.activeChartTypeIndex = null
				this.windowTypeIndex = null
				this.setupForm = {
					pageId: null,
					componentName: null,
					analyticsType: null,
					remark: null,
					dateUnit: null,
					chartType: null,
					showItem: [],
					windowType: null,
					sortNo: null,
					saveType: 'comment'
				}
				this.setupForm.analyticsType = this.$route.path.split('/').pop()
				if (done) done()
			},

			launchSubmit() {
				console.log('发起请求');
				this.$EventBus.$emit('askComponentQueryJson')
			},

			submitForm(requestJson) {
				let params = {
					...this.setupForm
				}
				new Promise((resolve, reject) =>{
					if(this.setupForm.saveType == 'comment') {
						this.$refs["setupForm"].validate(valid =>{
							if(valid) {
								resolve(true)
							}else {
								resolve(false)
							}
						})
					}else if(this.setupForm.saveType == 'bookmark'){
						this.$refs["bookmarkForm"].validate(valid =>{
							if(valid) {
								resolve(true)
							}else {
								resolve(false)
							}
						})
					}
				}).then(isValid =>{
					console.log(isValid);
					if(isValid) {
						params.showItem = this.setupForm.showItem.join(",")
						params.queryRule = requestJson;
            this.setupForm.queryRule = requestJson;
            if(this.setupForm.saveType == 'comment'){
              if (this.setupForm.id != null) {
                updateItems(this.setupForm).then(response => {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                });
              } else {
                addItems(params).then(response => {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.setupComponentVisible = false
                  this.getComponentsByPageid()
                  this.reset()
                });
              }
            }
            else if(this.setupForm.saveType == 'bookmark'){
              if (this.setupForm.id != null) {
                updateMark(this.setupForm).then(response => {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                });
              } else {
                addMark(this.setupForm).then(response => {
                  this.msgSuccess("新增成功");
                  this.setupComponentVisible = false
                  this.getComponentsByPageid()
                  this.reset()
                });
              }
            }
						this.closeSelectedTag()
					}else {
            this.msgError("请正确填写表单信息");
					}
				})
			},

			cancel() {
				this.reset()
				this.setupComponentVisible = false
			},

			windowTypeChangeFun(index, item) {
				if (this.setupForm.chartType != 6 && item.dictValue == 'small') return
				this.setupForm.windowType = item.dictValue
				this.windowTypeIndex = index
			},

			closeSelectedTag() {
				this.$store.dispatch('tagsView/delView', this.$route).then(({
					visitedViews
				}) => {
					this.$router.push('/analytics/team')
				})
			},

			getUserPageData() {
				let parmas = {};
				listPage(parmas).then(response => {
					this.userPageOptions = response.rows
				})
			},
		},
	};
</script>
<style lang="scss">
	.page-sensorsdata {
		background-color: #F0F2F5;
		box-sizing: border-box;
		padding: 10px 20px 20px;
		overflow-y: scroll;
		height: calc(100vh - 84px);

		&::-webkit-scrollbar {
			width: 0 !important
		}

		.pageheader {
			width: 100%;

			height: 50px;

			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 15px 0;

			font-weight: 500;
			font-size: 24px;
			line-height: 36px;
			color: #1f2d3d;

			.pageheader-right {
				.btn {
					color: #007aff;
					cursor: pointer;
					font-size: 14px;
				}
			}
		}

		.sendorsdata-body {
			background-color: #FFFFFF;
		}
	}

	.setup-component {

		.el-dialog__header {
			box-sizing: border-box;
			border-bottom: 1px solid #E9F0F7;
			padding-left: 50px;

			.setupComponentTitle {
				display: flex;

				.title-item {
					margin-right: 24px;
					color: #8492a6;
					font-size: 14px;
					position: relative;
				}

				.active {
					color: #1f2d3d;

					&::after {
						content: "";
						position: absolute;
						width: 100%;
						border-bottom: 2px solid #F5B126;
						bottom: -10px;
						left: 0;
					}
				}
			}
		}

		.el-dialog__body {
			box-sizing: border-box;
			width: 100%;
			padding: 30px 50px 10px;

			.el-form-item__label {
				font-weight: normal;
			}

			.chartype {
				.chart-type-item {
					height: 48px;
					width: 54px;
					border: 1px solid #eeeeee;
					margin-right: 10px;
					display: inline-flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					box-sizing: border-box;
					padding-top: 4px;
					border-radius: 4px;
					color: #97A7BD;
					position: relative;
					cursor: pointer;

					&>span {
						font-size: 11px;
						line-height: 16px;
						margin-top: 6px;
					}

					&>i {
						font-size: 14px;
					}

					.check-tag {
						position: absolute;
						right: 0;
						top: 0;
						display: inline-block;
						border-top: 22px solid #F5B126;
						border-left: 25px solid transparent;

						&>i {
							position: absolute;
							top: -20px;
							left: -12px;
							font-size: 9px;
							color: #FFFFFF;
						}
					}
				}

				.active {
					border: 1px solid #F5B126;
					color: #F5B126;
				}

				.forbidden {
					background-color: #eff2f7;
					color: #c0ccda;
					border: 1px solid #e3ecf6;
					// pointer-events: none;
					cursor: not-allowed;
				}

			}

			.window-type {
				.window-type-item {
					display: inline-flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					height: 59px;
					width: 94px;
					color: #97A7BD;
					border: 1px solid #E3ECF6;
					margin-right: 20px;
					border-radius: 4px;
					box-sizing: border-box;
					position: relative;

					.window-type-back {
						height: 24px;
						width: 76px;
						margin-bottom: 4px;
						background-repeat: no-repeat;
						background-size: contain;
					}

					.small {
						background-image: url(https://family.demo.sensorsdata.cn/new/47f9d6c72e6c9f07bedd4894f78216d6.svg);
					}

					.medium {
						background-image: url(https://family.demo.sensorsdata.cn/new/cd397327b88d20cafdec4aa222fa496f.svg);
					}

					.big {
						background-image: url(https://family.demo.sensorsdata.cn/new/07554ae4c9c9e4d4f324dc0af0a2f3db.svg);
					}

					.label {
						font-size: 11px;
						line-height: 14px;
					}

					.check-tag {
						position: absolute;
						right: 0;
						top: 0;
						display: inline-block;
						border-top: 22px solid #F5B126;
						border-left: 25px solid transparent;

						&>i {
							position: absolute;
							top: -20px;
							left: -12px;
							font-size: 9px;
							color: #FFFFFF;
						}
					}
				}

				.active {
					border: 1px solid #F5B126;
					color: #F5B126;
				}

				.forbidden {
					background-color: #eff2f7;
					cursor: not-allowed;
					color: #c0ccda;
				}
			}

		}
	}
</style>
